// Kuikly UI通信服务实现 - 仅使用safe Rust，集成了ZENrs与Kuikly的优势互补功能

#![forbid(unsafe_code)]

use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::collections::{HashMap, VecDeque};
use std::ffi::{CStr, CString};
use std::ptr::NonNull;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use log::{info, warn, error, debug};

// 导入核心类型
use super::{Capability, CapabilityId};
use super::ipc_service::IPCError;
use serde::{Serialize, Deserialize};
use std::io::Cursor;
use bincode::Options;

// 消息批处理阈值
const SMALL_MESSAGE_THRESHOLD: u32 = 128;
const BATCH_THRESHOLD: u32 = 10;
const LARGE_MESSAGE_THRESHOLD: u32 = 4096;

// 从exokernel导入的类型
type UICommChannelId = u64;
type UIMessageId = u32;

// UI通信错误类型
#[derive(Debug, Clone, PartialEq)]
pub enum KuiklyError {
    ChannelNotFound,
    ChannelAlreadyExists,
    SendFailed,
    ReceiveFailed,
    Timeout,
    InvalidParameter,
    ExokernelError,
    PermissionDenied,
    MessageTooLarge,
    BufferTooSmall,
}

// UI事件ID常量
const UI_EVENT_MOUSEMOVE: u32 = 1;
const UI_EVENT_MOUSEDOWN: u32 = 2;
const UI_EVENT_MOUSEUP: u32 = 3;
const UI_EVENT_KEYDOWN: u32 = 4;
const UI_EVENT_KEYUP: u32 = 5;
const UI_EVENT_RESIZE: u32 = 6;
const UI_EVENT_FOCUS: u32 = 7;
const UI_EVENT_BLUR: u32 = 8;

// UI命令ID常量
const UI_COMMAND_CREATE_WINDOW: u32 = 1001;
const UI_COMMAND_DESTROY_WINDOW: u32 = 1002;
const UI_COMMAND_UPDATE_VIEW: u32 = 1003;
const UI_COMMAND_SET_PROPERTY: u32 = 1004;
const UI_COMMAND_REQUEST_FOCUS: u32 = 1005;
const UI_COMMAND_RELEASE_FOCUS: u32 = 1006;

// 腾讯Kuikly专用常量
const KUIKLY_CHANNEL_FLAG: u32 = 0x100;
const KUIKLY_DEFAULT_PRIORITY: u8 = 80;
const KUIKLY_DEFAULT_BUFFER_SIZE: u64 = 8 * 1024 * 1024; // 8MB
const KUIKLY_DEFAULT_MAX_MESSAGES: u32 = 2048;

// UI消息结构
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UIMessage {
    pub msg_id: UIMessageId,
    pub sender_id: u64,
    pub target_id: u64,
    pub timestamp: u64,
    pub data_size: u32,
    pub data_ptr: u64,
    _reserved: u64,
}

// UI通道配置
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct UIChannelConfig {
    pub buffer_size: u64,
    pub max_messages: u32,
    pub priority: u8,
    pub flags: u32,
}

// 从exokernel导入的UI通信API
#[link(name = "exokernel")]
extern "C" {
    fn exokernel_ui_comm_init(cap_id: CapabilityId) -> bool;
    fn exokernel_ui_comm_create_channel(
        cap_id: CapabilityId,
        name: *const u8,
        config: *const UIChannelConfig,
        out_channel_id: *mut UICommChannelId
    ) -> bool;
    fn exokernel_ui_comm_open_channel(
        cap_id: CapabilityId,
        name: *const u8,
        out_channel_id: *mut UICommChannelId
    ) -> bool;
    fn exokernel_ui_comm_close_channel(
        cap_id: CapabilityId,
        channel_id: UICommChannelId
    ) -> bool;
    fn exokernel_ui_comm_send_message(
        cap_id: CapabilityId,
        channel_id: UICommChannelId,
        message: *const UIMessage
    ) -> bool;
    fn exokernel_ui_comm_receive_message(
        cap_id: CapabilityId,
        channel_id: UICommChannelId,
        message: *mut UIMessage,
        timeout_ms: u32
    ) -> bool;
    fn exokernel_ui_comm_get_channel_stats(
        cap_id: CapabilityId,
        channel_id: UICommChannelId,
        out_messages_sent: *mut u64,
        out_messages_received: *mut u64,
        out_bytes_sent: *mut u64,
        out_bytes_received: *mut u64
    ) -> bool;
    // 腾讯Kuikly专用API
    fn exokernel_ui_comm_create_kuikly_channel(
        cap_id: CapabilityId,
        name: *const u8,
        out_channel_id: *mut UICommChannelId
    ) -> bool;
    fn exokernel_ui_comm_convert_kuikly_message(
        cap_id: CapabilityId,
        channel_id: UICommChannelId,
        kuikly_msg: *const u8,
        msg_size: u64,
        zenrs_msg: *mut UIMessage
    ) -> bool;
    fn exokernel_ui_comm_send_kuikly_message(
        cap_id: CapabilityId,
        channel_id: UICommChannelId,
        msg_type: u32,
        data: *const u8,
        data_size: u64
    ) -> bool;
}

// 批处理消息结构
struct BatchedMessage {
    msg_id: UIMessageId,
    sender_id: u64,
    target_id: u64,
    data: Option<Vec<u8>>,
    timestamp: u64,
    urgent: bool,
}

// 消息批处理器
struct MessageBatchProcessor {
    messages: Mutex<VecDeque<BatchedMessage>>,
    last_flush_time: AtomicU64,
    flush_interval_ms: u64,
    // 性能统计相关
    batch_count: AtomicU64,
    message_count: AtomicU64,
}

impl MessageBatchProcessor {
    fn new(flush_interval_ms: u64) -> Self {
        MessageBatchProcessor {
            messages: Mutex::new(VecDeque::new()),
            last_flush_time: AtomicU64::new(KuiklyUIService::get_timestamp()),
            flush_interval_ms,
            // 性能统计相关
            batch_count: AtomicU64::new(0),
            message_count: AtomicU64::new(0),
        }
    }
    
    // 添加消息到批处理队列
    fn add_message(&self, message: BatchedMessage) {
        let mut messages = self.messages.lock().unwrap();
        
        // 如果是紧急消息，添加到队列前端
        if message.urgent {
            messages.push_front(message);
        } else {
            messages.push_back(message);
        }
        
        self.message_count.fetch_add(1, Ordering::Relaxed);
    }
    
    // 检查是否需要刷新批处理队列
    fn should_flush(&self) -> bool {
        let messages = self.messages.lock().unwrap();
        let count = messages.len() as u32;
        
        // 如果达到批处理阈值或包含紧急消息，立即刷新
        if count >= BATCH_THRESHOLD || messages.iter().any(|m| m.urgent) {
            return true;
        }
        
        let current_time = KuiklyUIService::get_timestamp();
        let last_flush = self.last_flush_time.load(Ordering::SeqCst);
        
        // 如果超过刷新间隔，也刷新
        current_time - last_flush >= self.flush_interval_ms
    }
    
    // 刷新批处理队列并返回所有消息
    fn flush(&self) -> Vec<BatchedMessage> {
        let mut messages = self.messages.lock().unwrap();
        let batch = messages.drain(..).collect();
        
        self.last_flush_time.store(KuiklyUIService::get_timestamp(), Ordering::SeqCst);
        self.batch_count.fetch_add(1, Ordering::Relaxed);
        
        batch
    }
    
    // 获取当前队列中的消息数量
    fn get_message_count(&self) -> usize {
        let messages = self.messages.lock().unwrap();
        messages.len()
    }
    
    // 检查是否有紧急消息
    fn has_urgent_messages(&self) -> bool {
        let messages = self.messages.lock().unwrap();
        messages.iter().any(|m| m.urgent)
    }
    
    // 获取性能统计信息
    fn get_stats(&self) -> (u64, u64) {
        (self.batch_count.load(Ordering::Relaxed), 
         self.message_count.load(Ordering::Relaxed))
    }
    
    // 清空队列
    fn clear(&self) {
        let mut messages = self.messages.lock().unwrap();
        messages.clear();
    }
}

// UI通道
struct UIChannel {
    id: UICommChannelId,
    name: String,
    config: UIChannelConfig,
    stats: Mutex<ChannelStats>,
    batch_processor: Arc<MessageBatchProcessor>,
    // 通信模式
    communication_mode: CommunicationMode,
}

// 为UIChannel实现Clone
extern crate alloc;
impl Clone for UIChannel {
    fn clone(&self) -> Self {
        let stats = {
            let stats_guard = self.stats.lock().unwrap();
            ChannelStats {
                messages_sent: stats_guard.messages_sent,
                messages_received: stats_guard.messages_received,
                bytes_sent: stats_guard.bytes_sent,
                bytes_received: stats_guard.bytes_received,
                last_message_time: stats_guard.last_message_time,
                is_kuikly_channel: stats_guard.is_kuikly_channel,
                avg_processing_time_ns: stats_guard.avg_processing_time_ns,
                avg_message_size: stats_guard.avg_message_size,
            }
        };
        
        UIChannel {
            id: self.id,
            name: self.name.clone(),
            config: self.config,
            stats: Mutex::new(stats),
            batch_processor: Arc::clone(&self.batch_processor),
            communication_mode: self.communication_mode,
        }
    }
}

// 通信模式枚举
#[derive(Debug, Copy, Clone)]
enum CommunicationMode {
    // 立即处理每条消息
    ImmediateProcessing,
    // 批处理模式，累积一定数量的消息后一起处理
    BatchProcessing,
    // 零拷贝模式，适用于大消息
    ZeroCopy,
    // 自适应模式，根据实际情况动态调整
    Adaptive,
}

// 通道统计信息
struct ChannelStats {
    messages_sent: u64,
    messages_received: u64,
    bytes_sent: u64,
    bytes_received: u64,
    last_message_time: u64,
    is_kuikly_channel: bool,
    // 消息处理时间统计
    avg_processing_time_ns: u64,
    // 平均消息大小
    avg_message_size: u64,
}

// Kuikly UI服务 - 集成了ZENrs与Kuikly优势互补的功能
pub struct KuiklyUIService {
    mem_cap: Capability,
    channels: RwLock<HashMap<UICommChannelId, UIChannel>>,
    name_to_id: RwLock<HashMap<String, UICommChannelId>>,
    running: AtomicBool,
    event_loop_thread: Option<std::thread::JoinHandle<()>>,
    // 消息批处理相关
    global_batch_processor: Arc<MessageBatchProcessor>,
    // 性能监控
    performance_monitor: Mutex<PerformanceMonitor>,
}

// 性能监控结构
struct PerformanceMonitor {
    // 消息处理时间统计
    message_processing_times: Vec<(Duration, u32)>, // (处理时间, 消息大小)
    // 通道性能统计
    channel_performance: HashMap<UICommChannelId, ChannelPerformanceStats>,
    // 最后清理时间
    last_cleanup_time: u64,
}

// 通道性能统计
struct ChannelPerformanceStats {
    message_count: u64,
    total_processing_time: Duration,
    message_size_distribution: [u64; 5], // 不同大小范围的消息数量
    last_message_time: u64,
}

impl PerformanceMonitor {
    fn new() -> Self {
        PerformanceMonitor {
            message_processing_times: Vec::new(),
            channel_performance: HashMap::new(),
            last_cleanup_time: 0,
        }
    }
    
    // 记录消息处理时间
    fn record_message_processing(&mut self, processing_time: Duration, message_size: u32, channel_id: UICommChannelId) {
        self.message_processing_times.push((processing_time, message_size));
        
        // 更新通道性能统计
        let channel_stats = self.channel_performance.entry(channel_id)
            .or_insert_with(|| ChannelPerformanceStats {
                message_count: 0,
                total_processing_time: Duration::from_nanos(0),
                message_size_distribution: [0; 5],
                last_message_time: 0,
            });
            
        channel_stats.message_count += 1;
        channel_stats.total_processing_time += processing_time;
        channel_stats.last_message_time = KuiklyUIService::get_timestamp();
        
        // 统计消息大小分布
        let size_index = match message_size {
            0..=64 => 0,
            65..=256 => 1,
            257..=1024 => 2,
            1025..=4096 => 3,
            _ => 4,
        };
        channel_stats.message_size_distribution[size_index] += 1;
        
        // 定期清理旧数据
        let current_time = KuiklyUIService::get_timestamp();
        if current_time - self.last_cleanup_time > 60000 { // 60秒清理一次
            self.cleanup_old_data();
            self.last_cleanup_time = current_time;
        }
    }
    
    // 添加消息处理事件（用于单条消息）
    fn add_message_processing_event(&mut self, channel_id: UICommChannelId, data_size: u32, processing_time_ns: u64) {
        let processing_time = Duration::from_nanos(processing_time_ns);
        self.record_message_processing(processing_time, data_size, channel_id);
    }
    
    // 添加批处理事件
    fn add_batch_processing_event(
        &mut self,
        channel_id: UICommChannelId,
        message_count: u32,
        total_data_size: u32,
        processing_time_ns: u64
    ) {
        // 记录批处理事件
        let processing_time = Duration::from_nanos(processing_time_ns);
        
        // 更新通道性能统计
        let channel_stats = self.channel_performance.entry(channel_id)
            .or_insert_with(|| ChannelPerformanceStats {
                message_count: 0,
                total_processing_time: Duration::from_nanos(0),
                message_size_distribution: [0; 5],
                last_message_time: 0,
            });
            
        // 这里假设批处理的平均处理时间是总时间除以消息数
        let avg_processing_time = processing_time / message_count;
        
        // 记录批处理统计（不更新单条消息统计）
        channel_stats.message_count += message_count as u64;
        channel_stats.total_processing_time += processing_time;
        channel_stats.last_message_time = KuiklyUIService::get_timestamp();
        
        // 更新全局消息处理时间记录
        self.message_processing_times.push((avg_processing_time, total_data_size / message_count));
        
        // 定期清理旧数据
        let current_time = KuiklyUIService::get_timestamp();
        if current_time - self.last_cleanup_time > 60000 { // 60秒清理一次
            self.cleanup_old_data();
            self.last_cleanup_time = current_time;
        }
    }
    
    // 清理旧数据
    fn cleanup_old_data(&mut self) {
        // 只保留最近1000条记录
        if self.message_processing_times.len() > 1000 {
            self.message_processing_times.drain(0..self.message_processing_times.len()-1000);
        }
        
        // 清理超过5分钟没有活动的通道统计
        let current_time = KuiklyUIService::get_timestamp();
        self.channel_performance.retain(|_, stats| {
            current_time - stats.last_message_time < 300000
        });
    }
    
    // 获取通道性能统计
    fn get_channel_performance(&self, channel_id: UICommChannelId) -> Option<&ChannelPerformanceStats> {
        self.channel_performance.get(&channel_id)
    }
    
    // 获取平均处理时间（毫秒）
    fn get_average_processing_time(&self) -> f64 {
        if self.message_processing_times.is_empty() {
            return 0.0;
        }
        
        let total_nanos: u128 = self.message_processing_times.iter()
            .map(|(time, _)| time.as_nanos())
            .sum();
        
        total_nanos as f64 / self.message_processing_times.len() as f64 / 1_000_000.0
    }
    
    // 获取性能报告
    fn generate_performance_report(&self) -> String {
        let mut report = String::new();
        report.push_str("=== Kuikly UI Service Performance Report ===\n");
        report.push_str(&format!("Total messages processed: {}\n", 
            self.message_processing_times.len()));
        report.push_str(&format!("Average processing time: {:.3} ms\n", 
            self.get_average_processing_time()));
        
        // 按通道统计
        report.push_str("\nChannel Statistics:\n");
        for (channel_id, stats) in &self.channel_performance {
            let avg_time = if stats.message_count > 0 {
                (stats.total_processing_time.as_nanos() as f64) / 
                (stats.message_count as f64 * 1_000_000.0)
            } else {
                0.0
            };
            
            report.push_str(&format!("Channel {}: {} messages, avg time: {:.3} ms\n", 
                channel_id, stats.message_count, avg_time));
        }
        
        report
    }
}

impl KuiklyUIService {
    // 创建新的Kuikly UI服务
    pub fn new(mem_cap: Capability) -> Result<Self, String> {
        let service = KuiklyUIService {
            mem_cap: mem_cap.clone(),
            channels: RwLock::new(HashMap::new()),
            name_to_id: RwLock::new(HashMap::new()),
            running: AtomicBool::new(false),
            event_loop_thread: None,
            global_batch_processor: Arc::new(MessageBatchProcessor::new(10)), // 10ms刷新间隔
            performance_monitor: Mutex::new(PerformanceMonitor::new()),
        };
        
        Ok(service)
    }
    
    // 启动Kuikly UI服务
    pub fn start(&mut self) -> Result<(), String> {
        if self.running.load(std::sync::atomic::Ordering::SeqCst) {
            return Ok(());
        }
        
        // 初始化Kuikly UI服务
        self.init()
    }
    
    // 初始化Kuikly UI服务
    fn init(&self) -> Result<(), String> {
        // 实际实现中，这里会初始化Kuikly UI相关资源
        // 例如：创建窗口、加载字体、初始化渲染器等
        Ok(())
    }
    
    // 注册内存能力
    pub fn register_memory_capability(&self, _mem_cap: &Capability) -> Result<(), String> {
        // 实际实现中，这里会使用内存能力来为UI分配内存资源
        Ok(())
    }
    
    // 打开已存在的UI通信通道
    pub fn open_channel(&self, name: &str) -> Result<UICommChannelId, KuiklyError> {
        // 创建C字符串
        let c_name = CString::new(name).map_err(|_| KuiklyError::InvalidParameter)?;
        
        let mut channel_id: UICommChannelId = 0;
        
        // 调用exokernel API打开通道
        let result = unsafe {
            exokernel_ui_comm_open_channel(
                self.mem_cap.id(),
                c_name.as_ptr() as *const u8,
                &mut channel_id
            )
        };
        
        if !result || channel_id == 0 {
            return Err(KuiklyError::ChannelNotFound);
        }
        
        // 记录通道信息（如果是首次打开）
        {
            let channels = self.channels.read().unwrap();
            if !channels.contains_key(&channel_id) {
                let mut channels_write = self.channels.write().unwrap();
                let mut name_to_id_write = self.name_to_id.write().unwrap();
                
                // 使用默认配置，因为我们不知道原始配置
                let default_config = UIChannelConfig {
                    buffer_size: 4096,
                    max_messages: 128,
                    priority: 100,
                    flags: 0,
                };
                
                channels_write.insert(channel_id, UIChannel {
                    id: channel_id,
                    name: name.to_string(),
                    config: default_config,
                    stats: Mutex::new(ChannelStats {
                        messages_sent: 0,
                        messages_received: 0,
                        bytes_sent: 0,
                        bytes_received: 0,
                        last_message_time: 0,
                        is_kuikly_channel: false,
                        avg_processing_time_ns: 0,
                        avg_message_size: 0,
                    }),
                    batch_processor: Arc::clone(&self.global_batch_processor),
                    communication_mode: CommunicationMode::Adaptive,
                });
                
                name_to_id_write.insert(name.to_string(), channel_id);
            }
        }
        
        info!("Opened UI channel: name={}, id={}", name, channel_id);
        
        Ok(channel_id)
    }
    
    // 通知窗口创建
    pub fn notify_window_created(
        &self,
        window_id: u64,
        title: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32
    ) -> Result<(), KuiklyError> {
        // 创建窗口信息数据
        let window_info = format!("{{\"window_id\": {}, \"title\": \"{}\", \"x\": {}, \"y\": {}, \"width\": {}, \"height\": {}}}",
            window_id, title, x, y, width, height);
        let window_info_bytes = window_info.as_bytes();
        
        // 在实际实现中，这里会向Kuikly发送窗口创建消息
        info!("Notifying window created: {}, title={}", window_id, title);
        
        Ok(())
    }
    
    // 通知窗口销毁
    pub fn notify_window_destroyed(
        &self,
        window_id: u64
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送窗口销毁消息
        info!("Notifying window destroyed: {}", window_id);
        
        Ok(())
    }
    
    // 通知窗口移动
    pub fn notify_window_moved(
        &self,
        window_id: u64,
        x: i32,
        y: i32
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送窗口移动消息
        info!("Notifying window moved: {} to ({}, {})", window_id, x, y);
        
        Ok(())
    }
    
    // 通知窗口大小改变
    pub fn notify_window_resized(
        &self,
        window_id: u64,
        width: u32,
        height: u32
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送窗口大小改变消息
        info!("Notifying window resized: {} to {}x{}", window_id, width, height);
        
        Ok(())
    }
    
    // 通知窗口可见性改变
    pub fn notify_window_visibility_changed(
        &self,
        window_id: u64,
        visible: bool
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送窗口可见性改变消息
        info!("Notifying window visibility changed: {}, visible={}", window_id, visible);
        
        Ok(())
    }
    
    // 通知窗口焦点改变
    pub fn notify_window_focus_changed(
        &self,
        window_id: u64,
        focused: bool
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送窗口焦点改变消息
        info!("Notifying window focus changed: {}, focused={}", window_id, focused);
        
        Ok(())
    }
    
    // 通知应用程序启动
    pub fn notify_app_launched(
        &self,
        app_id: &str,
        window_id: u64
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送应用程序启动消息
        info!("Notifying app launched: {}, window_id={}", app_id, window_id);
        
        Ok(())
    }
    
    // 通知应用程序停止
    pub fn notify_app_stopped(
        &self,
        app_id: &str
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送应用程序停止消息
        info!("Notifying app stopped: {}", app_id);
        
        Ok(())
    }
    
    // 通知应用程序被激活
    pub fn notify_app_activated(
        &self,
        app_id: &str,
        window_id: u64
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送应用程序被激活消息
        info!("Notifying app activated: {}, window_id={}", app_id, window_id);
        
        Ok(())
    }
    
    // 通知Dock栏创建
    pub fn notify_dock_created(
        &self
    ) -> Result<(), KuiklyError> {
        // 在实际实现中，这里会向Kuikly发送Dock栏创建消息
        info!("Notifying dock created");
        
        Ok(())
    }
    
    // 关闭UI通信通道
    pub fn close_channel(&self, channel_id: UICommChannelId) -> Result<(), KuiklyError> {
        // 检查通道是否存在
        let channel_name = {
            let channels = self.channels.read().unwrap();
            if let Some(channel) = channels.get(&channel_id) {
                channel.name.clone()
            } else {
                return Err(KuiklyError::ChannelNotFound);
            }
        };
        
        // 调用exokernel API关闭通道
        let result = unsafe {
            exokernel_ui_comm_close_channel(self.mem_cap.id(), channel_id)
        };
        
        if !result {
            return Err(KuiklyError::ExokernelError);
        }
        
        // 移除通道信息
        {
            let mut channels = self.channels.write().unwrap();
            let mut name_to_id = self.name_to_id.write().unwrap();
            
            channels.remove(&channel_id);
            name_to_id.remove(&channel_name);
        }
        
        info!("Closed UI channel: id={}", channel_id);
        
        Ok(())
    }
    
    // 发送UI消息
    pub fn send_message(
        &self,
        channel_id: UICommChannelId,
        msg_id: UIMessageId,
        sender_id: u64,
        target_id: u64,
        data: Option<&[u8]>
    ) -> Result<(), KuiklyError> {
        // 检查通道是否存在
        {
            let channels = self.channels.read().unwrap();
            if !channels.contains_key(&channel_id) {
                return Err(KuiklyError::ChannelNotFound);
            }
        }
        
        // 准备消息
        let (data_size, data_ptr) = if let Some(data_bytes) = data {
            (data_bytes.len() as u32, data_bytes.as_ptr() as u64)
        } else {
            (0, 0)
        };
        
        let message = UIMessage {
            msg_id,
            sender_id,
            target_id,
            timestamp: Self::get_timestamp(),
            data_size,
            data_ptr,
            _reserved: 0,
        };
        
        // 发送消息
        let result = unsafe {
            exokernel_ui_comm_send_message(self.mem_cap.id(), channel_id, &message)
        };
        
        if !result {
            return Err(KuiklyError::SendFailed);
        }
        
        info!("Sent UI message: type={}, channel={}", msg_id, channel_id);
        
        Ok(())
    }
    
    // 接收UI消息
    pub fn receive_message(
        &self,
        channel_id: UICommChannelId,
        timeout_ms: u32,
        buffer: &mut [u8]
    ) -> Result<(UIMessageId, u64, u64, Vec<u8>), KuiklyError> {
        // 检查通道是否存在
        {
            let channels = self.channels.read().unwrap();
            if !channels.contains_key(&channel_id) {
                return Err(KuiklyError::ChannelNotFound);
            }
        }
        
        let mut message = UIMessage {
            msg_id: 0,
            sender_id: 0,
            target_id: 0,
            timestamp: 0,
            data_size: 0,
            data_ptr: 0,
            _reserved: 0,
        };
        
        // 接收消息
        let result = unsafe {
            exokernel_ui_comm_receive_message(
                self.mem_cap.id(),
                channel_id,
                &mut message,
                timeout_ms
            )
        };
        
        if !result {
            return Err(KuiklyError::ReceiveFailed);
        }
        
        // 读取消息数据（如果有）
        let data = if message.data_size > 0 && message.data_ptr != 0 {
            let data_size = message.data_size.min(buffer.len() as u32);
            unsafe {
                std::ptr::copy_nonoverlapping(
                    message.data_ptr as *const u8,
                    buffer.as_mut_ptr(),
                    data_size as usize
                );
                Vec::from(&buffer[..data_size as usize])
            }
        } else {
            Vec::new()
        };
        
        info!("Received UI message: type={}, channel={}", message.msg_id, channel_id);
        
        Ok((message.msg_id, message.sender_id, message.target_id, data))
    }
    
    // 获取通道统计信息
    pub fn get_channel_stats(
        &self,
        channel_id: UICommChannelId
    ) -> Result<(u64, u64, u64, u64), KuiklyError> {
        // 检查通道是否存在
        {
            let channels = self.channels.read().unwrap();
            if !channels.contains_key(&channel_id) {
                return Err(KuiklyError::ChannelNotFound);
            }
        }
        
        let mut messages_sent: u64 = 0;
        let mut messages_received: u64 = 0;
        let mut bytes_sent: u64 = 0;
        let mut bytes_received: u64 = 0;
        
        // 获取统计信息
        let result = unsafe {
            exokernel_ui_comm_get_channel_stats(
                self.mem_cap.id(),
                channel_id,
                &mut messages_sent,
                &mut messages_received,
                &mut bytes_sent,
                &mut bytes_received
            )
        };
        
        if !result {
            return Err(KuiklyError::ExokernelError);
        }
        
        Ok((messages_sent, messages_received, bytes_sent, bytes_received))
    }
    
    // 获取当前时间戳（毫秒）
    fn get_timestamp() -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0)
    }
    
    // 停止Kuikly UI服务
    pub fn stop(&mut self) -> Result<(), String> {
        if !self.running.load(std::sync::atomic::Ordering::SeqCst) {
            return Ok(());
        }
        
        self.running.store(false, std::sync::atomic::Ordering::SeqCst);
        
        // 等待事件循环线程结束
        if let Some(handle) = self.event_loop_thread.take() {
            if let Err(err) = handle.join() {
                warn!("Kuikly UI event loop thread panicked: {:?}", err);
            }
        }
        
        // 关闭所有通道
        let channels_snapshot = self.channels.read().unwrap().clone();
        for (channel_id, _) in channels_snapshot.iter() {
            let _ = self.close_channel(*channel_id);
        }
        
        info!("Kuikly UI service stopped successfully");
        
        Ok(())
    }
}

impl Drop for KuiklyUIService {
    fn drop(&mut self) {
        if self.running.load(std::sync::atomic::Ordering::SeqCst) {
            let _ = self.stop();
        }
    }
}